import axios from "axios";

const request = axios.create({
  timeout: 5000,
  timeoutErrorMessage: "请求超时",
});
request.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    if (error && error.response) {
      // 1.公共错误处理
      // 2.根据响应码具体处理
      switch (error.response.status) {
        case 400:
          error.message = "请求错误";
          break;
        case 401:
          window.location.href = "/login";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = "请求的资源不存在";
          break;
        case 500:
          error.message = "服务端错误";
          break;
        case 8001:
          error.message = "用户业务错误";
          break;
        case 8002:
          error.message = "医生业务错误";
          break;
        case 8003:
          error.message = "公共业务错误";
          break;
        case 9001:
          error.message = "服务端错误";
          break;
        case 9999:
          error.message = "登录状态失效，请重新登录服务端错误";
          break;
        default:
          error.message = `连接错误${error.response.status}`;
      }
    }
    if (JSON.stringify(error).includes("timeout")) {
      console.log("网络错误，请重试");
    }
    error.message = "连接服务器失败";
    return Promise.reject(error);
  }
);

export default request;
